package com.xzlf.config;

import com.xzlf.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class ScheduledConfig implements SchedulingConfigurer {

    @Autowired
    private Map<String, TaskService> taskMap;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        for (String key : taskMap.keySet()) {
            taskRegistrar.addTriggerTask(
                    () ->{
                        taskMap.get(key).execute();
                        try {
                            TimeUnit.SECONDS.sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    },
                    triggerContext -> {
                        CronTrigger cronTrigger = new CronTrigger("0/5 * * * * ?");
                        Date date = cronTrigger.nextExecutionTime(triggerContext);
                        return date;
                    }
            );
        }
    }
}
